﻿using System;
using System.Linq;
using System.Web.Mvc;
using CP_SchoolForChildren_v0._1.Controllers.FE;
using CP_SchoolForChildren_v0._1.Controllers.Support;
using CP_SchoolForChildren_v0._1.Models.DataModel;
using CP_SchoolForChildren_v0._1.Models.RelatedModel;

namespace CP_SchoolForChildren_v0._1.Controllers.BE
{
    public class UsersManagementController : Controller
    {

        FunctionController fc = new FunctionController();
        CheckUserProfile cup = new CheckUserProfile();
        SFCMessage sfcMessage = new SFCMessage();

        [Authorize(Roles = "Admin")]
        public ActionResult Index()
        {
            return View();
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public JsonResult ListUser(string keywords, int jtStartIndex, int jtPageSize, string jtSorting)
        {
            try
            {
                {
                    if (keywords == null)
                    {
                        keywords = "";
                    }
                    var record = fc.db.Users.
                        Where(u => u.UserName.Contains(keywords));

                    //Get Totalrow
                    var totalrow = record.Count();
                    //Paging
                    var temp = record.OrderUsingSortExpression(jtSorting).
                        Skip(jtStartIndex).Take(jtPageSize);

                    return Json(new { Result = "OK", Records = temp.ToList(), TotalRecordCount = totalrow });
                }
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.ToString() });
            }
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public JsonResult CreateUser(User user)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "Form is not valid! " +
                        "Please correct it and try again."
                    });
                }       
                if(cup.isUsernameExist(user.UserName))
                {
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "Username " + user.UserName +" đã tồn tại"
                    });
                }
                if (cup.isEmailExist(user.Email))
                {
                    return Json(new
                    {
                        Result = "ERROR",
                        Message = "Địa chỉ email" + user.Email + " đã tồn tại"
                    });
                }
                                  
                {
                    user.Password = AccountController.GenerateMD5HashCode(user.Password);
                    var record = fc.db.Users.Add(user);
                    fc.db.SaveChanges();
                    return Json(new { Result = "OK", Record = record });
                }
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.ToString() });
            }
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public JsonResult UpdateUser(User user)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
                }

                var temp = fc.db.Users.Where(u => u.UserID != user.UserID).ToList();

                if (temp.Any(u => u.UserName == user.UserName))
                {
                        return Json(new
                        {
                            Result = "ERROR",
                            Message = "Username " + user.UserName + " đã tồn tại"
                        });
                }
                if (temp.Any(u => u.Email == user.Email))
                {
                        return Json(new
                        {
                            Result = "ERROR",
                            Message = "Địa chỉ email" + user.Email + " đã tồn tại"
                        });
                }
                    fc.db.Entry(user).State = System.Data.EntityState.Modified;
                    var record = fc.db.SaveChanges();
                    return Json(new { Result = "OK", Record = record });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.ToString() });
            }
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public JsonResult DeleteUser(User user)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
                }
                    fc.db.Configuration.ProxyCreationEnabled = false;
                    fc.db.Entry(user).State = System.Data.EntityState.Deleted;
                    var record = fc.db.SaveChanges();
                    return Json(new { Result = "OK", Record = record });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.ToString() });
            }
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public JsonResult GetRoleOptions()
        {
            try
            {
                var record = fc.db.UserRoles.Select(r => new { DisplayText = r.RoleName, Value = r.RoleID });
                return Json(new { Result = "OK", Options = record });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.ToString() });
            }
        }




    }
}
